<template>
  <div style="width: 100%">
    <div id="deawer">
      <v-tableTitle
        :btnConfig="btnConfig"
        @cancel="cancel"
        @btnTableData="btnTableData"
        @poFill="poFill"
        @save="save"
        v-if="flag"
      ></v-tableTitle>
      <v-tableTitle
        :btnConfig="btnConfig1"
        @cancel="cancel"
        @btnTableData="btnTableData"
        @look="look"
        @save="save"
        @allReception="allReception"
        @closeAsn="closeAsn"
        @generate="generate"
        @mScanGather="mScanGather"
        @mScanRetreat="mScanRetreat"
        @receivingrotation="receivingrotation"
        @newActivation="newActivation"
        @scanGather="scanGather"
        @scanRetreat="scanRetreat"
        @mPrintShelves="mPrintShelves"
        v-else
      ></v-tableTitle>
      <div class="detailBox" style="height:300px">
        <v-detail ref="detail"></v-detail>
      </div>
      <div class="detailListBox">
        <v-detailList ref="detailList"></v-detailList>
      </div>
      <el-dialog
        :modal="false"
        :visible.sync="dialogFlag"
        title=""
        top="0"
        v-dialogDrag
        @close="dialogFlag = false"
        :close-on-click-modal="false"
        :append-to-body="true"
        width="900px"
      >
        <v-tableTitle
          :btnConfig="btnConfig2"
          :title="''"
          @completePerform="completePerform"
          @completeTask="completeTask"
          @changeShelvesValue="changeShelvesValue"
        ></v-tableTitle>
        <v-table
          :pageSize="pageSize"
          :page="page"
          :tableConfig="tableConfig1"
          :tableData="tableData"
          :total="total"
          @findData="getTableData"
          @getTableData="getTableData"
          @searhData="searhData"
          @selectData="selectData"
          @upData="getTableData"
          ref="table"
        ></v-table>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import baseMixin from "@/mixins/BaseMixin";
import config from "../Config";
import skipMixin from "@/mixins/SkipMixin";

import tableTitle from "commons/TableTitle";
import detail from "../details/Detail";
import detailList from "../detailsList/DetailList";
import table from "commons/Table";

export default {
  name: "asnDeawer",
  mixins: [baseMixin, config],
  data() {
    return {
      loading: false,
      flag: false,
      dialogTableVisible: false,
      poUrl: "queryListOfPoModal/true/1/true/true/",
      lookUrl: "/queryListOfTaskDetailModal/",
      routeData: {},
      dialogFlag: false,
      tableData: [],
      pageSize: 10,
      page: 1,
      total: 10,
      tableSearhData: {},
      tableUrl: "",
      tableSelectData: [],
    };
  },
  computed: {
    tableConfig1() {
      return [
        {
          label: this.$t('in.taskdetailkey'),
          prop: "taskdetailkey",
          input: "input",
          disabled: false,
        },
        {
          label: this.$t('config.shipper'),
          prop: "storerkey",
          input: "input",
          disabled: false,
        },
        {
          label: this.$t('config.sku'),
          prop: "sku",
          input: "input",
          disabled: false,
        },
        {
          label: this.$t('in.qty'),
          prop: "qty",
          eidtFlag: true,
          verify(value, that) {
            if (value === "") {
              that.$message.error(this.$tj('in.qtyreceived','app.emptyMes'));
              return false;
            } else {
              var re = /^[0-9]*$/;
              let te = value;
              let flag = re.test(te);
              if (flag) {
                if (value < 0) {
                  that.$message.error(this.$t('app.inputGreaterZeroNumberPlease'));
                  return false;
                } else {
                  value = parseInt(value);
                  return true;
                }
              } else {
                that.$message.error(this.$t('app.inputGreaterZeroNumberPlease'));
                return false;
              }
            }
          },
        },
        {
          label: this.$t('bill.lot'),
          prop: "lot",
          input: "input",
          disabled: false,
        },
        {
          label: this.$t('config.toLoc'),
          prop: "toloc",
          eidtFlag: true,
          verify(value, that) {
            value = value.replace(/\s*/g, "");
            if (value === "") {
              that.$message.error(this.$tj('config.loc','app.emptyMes'));
              return false;
            } else {
              return true;
            }
          },
        },
        {
          label: this.$t('in.toid'),
          prop: "toid",
          disabled: false,
          input: "input",
        },
        {
          label: this.$t('common.status'),
          prop: "status",
          input: "select",
          disabled: false,
          options: this.getOptions("codelkup/TMSTATUS"),
        },
        {
          label: this.$t('outbound.fromloc'),
          prop: "fromloc",
          input: "input",
          disabled: false,
        },
        {
          label: this.$t('in.fromid'),
          prop: "fromid",
          input: "input",
          disabled: false,
        },
        {
          label: this.$t('in.priority'),
          prop: "priority",
          input: "select",
          disabled: false,
          options: this.getOptions("codelkup/TMPRIORITY"),
        },
      ];
    },
    btnConfig() {
      return [
        { label: this.$t('common.save'), certigier: !this.btnPermNameList.includes('WM010113'),  invalid: "save" },
        { label: this.$t('common.cancel'), certigier: !this.btnPermNameList.includes('WM010114'),  invalid: "cancel" },
        {
          type: "table",
          certigier: this.poStatus||!this.btnPermNameList.includes('WM010134'),
          label: this.$t('in.po'),
          invalid: "po",
          tableConfig: [
            {
              label: this.$t('in.pokey'),
              prop: "pokey",
              input: "input",
              disabled: false,
            },
            {
              label: this.$t('in.storerkey'),
              prop: "storerkey",
              input: "input",
              disabled: false,
            },
            {
              label: this.$t('common.status'),
              prop: "status",
              input: "select",
              disabled: true,
              options: this.getOptions("codelkup/POSTATUS"),
            },
            {
              label: this.$t('common.type'),
              prop: "potype",
              input: "select",
              disabled: true,
              options: this.getOptions("codelkup/POTYPE"),
            },
            {
              label: this.$t('in.podate'),
              prop: "podate",
              input: "date",
              disabled: false,
            },
            {
              label: this.$t('in.expectedreceiptdate'),
              prop: "expectedreceiptdate",
              input: "date",
              disabled: false,
            },
            {
              label: this.$t('config.supplier'),
              prop: "sellername",
              input: "input",
              disabled: false,
            },
            {
              label: this.$t('in.externpokey'),
              prop: "externpokey",
              input: "input",
              disabled: false,
            },
            {
              label: this.$t('in.sellersreference'),
              prop: "sellersreference",
              input: "input",
              disabled: false,
            },
            {
              label: this.$t('in.surplusqty'),
              prop: "surplusqty",
              input: "input",
              disabled: false,
            },
          ],
          url: "queryListOfPoModal/true/1/true/true/",
        },
      ];
    },
    btnConfig1() {
      return [
        { label: this.$t('common.save'), certigier: !this.btnPermNameList.includes('WM010113'),  invalid: "save" },
        { label: this.$t('common.cancel'), certigier: !this.btnPermNameList.includes('WM010114'),  invalid: "cancel" },
        {
          label: this.$t('in.lookPutaway'),
          invalid: "look",
          certigier: this.actionStatus||!this.btnPermNameList.includes('WM010115'),
        },
        // {
        //   type: "tableDialog",
        //   label: this.$t('in.lookPutaway'),
        //   invalid: "po",
        //   certigier: this.actionStatus,
        //   url: "queryListOfTaskDetailModal/",
        // },
        {
          type: "more",
          label: this.$t('common.moreMenu'),
          invalid: "down",
          certigier: !this.btnPermNameList.includes('WM010116'),
          btnConfig: [
            {
              label: this.$t('in.allReception'),
              certigier: this.actionStatus||!this.btnPermNameList.includes('WM010117'),
              invalid: "allReception",
            },
            {
              label: this.$t('in.newActivation'),
              certigier: this.actionStatus||!this.btnPermNameList.includes('WM010118'),
              invalid: "newActivation",
            },
            {
              label: this.$t('in.closeAsn'),
              certigier: this.actionStatus||!this.btnPermNameList.includes('WM010119'),
              invalid: "closeAsn",
            },
            {
              label: this.$t('in.scanGather'),
              certigier: this.actionStatus||!this.btnPermNameList.includes('WM010120'),
              invalid: "scanGather",
            },
            {
              label: this.$t('in.scanRetreat'),
              certigier: this.actionStatus||!this.btnPermNameList.includes('WM010121'),
              invalid: "scanRetreat",
            },
            {
              label: this.$t('in.receivingrotation'),
              certigier: this.actionStatus||!this.btnPermNameList.includes('WM010122'),
              invalid: "receivingrotation",
            },
            {
              label: this.$t('in.generate'),
              certigier: this.actionStatus||!this.btnPermNameList.includes('WM010123'),
              invalid: "generate",
            },
            {
              label: this.$t('in.mPrintShelves'),
              certigier: this.actionStatus||!this.btnPermNameList.includes('WM010124'),
              invalid: "mPrintShelves",
            },

            /*{
              label: "单件盲扫收货",
              certigier: this.blindActionStatus,
              invalid: "mScanGather"
            },
            {
              label: "单件盲扫退货",
              certigier: this.blindActionStatus,
              invalid: "mScanRetreat"
            }*/
          ],
        },
      ];
    },
    btnConfig2() {
      return [
        {
          label: this.$t('in.completeTask'),
          certigier: !this.btnPermNameList.includes('WM010132'),
          invalid: "completeTask",
        },
        /*{
          label: "执行完成",
          invalid: "completePerform",
        },*/
        {
          label: this.$t('common.save'),
          certigier: !this.btnPermNameList.includes('WM010133'),
          invalid: "changeShelvesValue",
        },
      ];
    },
  },
  created() {},
  methods: {
    //全部接收
    async allReception() {
      try {
        let res = await this.$api.get(
          `/asnReceiveAll/${this.routeData.receiptkey}`
        );
        
          this.$message.success(res.returnMgr);
          this.$refs.detailList.$children[1].getTableData(1, {});
        
      } catch (e) {
        this.$message.error(e);
      }
    },
    //重新激活ASN/收货单
    async newActivation() {
      try {
        let res = await this.$api.get(
          `/asnReactivation/${this.routeData.receiptkey}`
        );
        
          this.$message.success(res.returnMgr);
        
      } catch (e) {
        this.$message.error(e);
      }
    },
    //结算/关闭ASN/收货单
    async closeAsn() {
      try {
        let res = await this.$api.get(
          `/asnCompleteClose/${this.routeData.receiptkey}`
        );
        
          this.$message.success(res.returnMgr);
        
      } catch (e) {
        this.$message.error(e);
      }
    },
    //生成上架
    async generate() {
      try {
        let res = await this.$api.get(
          `/genPutawayTask/${this.routeData.receiptkey}`
        );
        
          this.$message.success(res.returnMgr);
        
      } catch (e) {
        this.$message.error(e);
      }
    },
    //单件扫描收货
    async scanGather() {
      let data = this.routeData;
      if (data.status == 9) {
        this.$message.error(this.$t('msg.msg33'));
        return;
      }

      if (data.status == 11) {
        this.$message.error(this.$t('msg.msg34'));
        return;
      }
      if (data.status == 15) {
        this.$message.error(this.$t('msg.msg35'));
        return;
      }
      if (data.status == 20) {
        this.$message.error(this.$t('msg.msg36'));
        return;
      }
      let whseid = this.$store.state.wms;
      let opeuser = this.$Cookies.get('user');
      let receiptkey = data.receiptkey;
      let name = "ONESCANNOREGISTER";
      //验证是否可以跳转
      let flag;
      await this.$api.get(`/validateUDF1/${receiptkey}`).then((res) => {
          flag = res.bean;
        
      });
      if (!flag) {
        this.$message.error(
          "收货单" + data.receiptkey + "不允许使用收货单件扫描"
        );
      } else {
        try {
          let res = await this.$api.get(`/getHttpUrl/${name}`);
          
            let url = `${res.bean}?whseid=${whseid}&opeuser=${opeuser}&receiptkey=${receiptkey}&benchNo=0001`;
            // this.$router.push({ name: "iframe", params: { url: url } });
            this.$router.push({
              name: "iframe",
              params: { url: url, title: "单件扫描收货" },
            });
          
        } catch (e) {
          this.$message.error(e);
        }
      }
    },
    //单件扫描退货
    async scanRetreat() {
      let self = this;
      let whseid = this.$store.state.wms;
      let users = this.$Cookies.get('user');
      let name = "ONESCANRET";
      let receiptkey = this.routeData.receiptkey;

      //验证是否可以跳转
      let flag;
      await self.$api.get(`/validateUDF1/${receiptkey}`).then((res) => {
          flag = res.bean;
      });

      if (flag) {
        self.$message.error(self.$t('msg.msg51',{no:receiptkey}))
      } else {
        try {
          let res = await this.$api.get(
            `/asnReturnGoods/${receiptkey}/${name}`
          );
          
            let storerKey = res.bean.storerkey;
            let externReceiptKey = res.bean.externreceiptkey;
            let type = res.bean.type;
            try {
              let response = await this.$api.get(`/getHttpUrl/${name}`);
                let url = `${response.bean}?whseid=${whseid}&users=${users}&receiptKey=${receiptkey}&storerKey=${storerKey}&externReceiptKey=${externReceiptKey}&type=${type}`;
                // this.$router.push({ name: "iframe", params: { url: url } });
                this.$router.push({
                  name: "iframe",
                  params: { url: url, title: "单件扫描退货" },
                });
            } catch (e) {
              this.$message.error(e);
            }
          
        } catch (e) {
          this.$message.error(e);
        }
      }
    },
    //收货单件回转
    async receivingrotation() {
      let data = this.routeData;
      /*if (data.status == 9) {
          this.$message.error(this.$t('msg.msg33'));
          return
      }*/

      if (data.status == 11) {
        this.$message.error(this.$t('msg.msg34'));
        return;
      }
      if (data.status == 15) {
        this.$message.error(this.$t('msg.msg35'));
        return;
      }
      if (data.status == 20) {
        this.$message.error(this.$t('msg.msg36'));
        return;
      }

      let whseid = this.$store.state.wms;
      let opeuser = this.$Cookies.get('user');
      let receiptkey = data.receiptkey;
      let storerkey = data.storerkey;
      let name = "RECEIVINGROTATION";
      try {
        let res = await this.$api.get(`/getHttpUrl/${name}`);
        
          let url = `${res.bean}?whseid=${whseid}&opeuser=${opeuser}&users=${opeuser}&receiptkey=${receiptkey}&storerkey=${storerkey}`;
          this.$router.push({
            name: "iframe",
            params: { url: url, title: "收货单件回转" },
          });
        
      } catch (e) {
        this.$message.error(e);
      }
    },
    //单件盲扫收货
    async mScanGather() {
      let whseid = this.$store.state.wms;
      let users = this.$Cookies.get('user');
      let name = "ONESCANNOREGISTER";
      let receiptkey = this.routeData.receiptkey;
      try {
        let res = await this.$api.get(`/asnReturnGoods/${receiptkey}/${name}`);
        
          try {
            let response = await this.$api.get(`/getHttpUrl/${name}`);
              let url = `${response.bean}?whseid=${whseid}&opeuser=${users}&receiptkey=${receiptkey}&name=${name}`;
              // this.$router.push({ name: "iframe", params: { url: url } });
              this.$router.push({
                name: "iframe",
                params: { url: url, title: "单件盲扫收货" },
              });
          } catch (e) {
            this.$message.error(e);
          }
        
      } catch (e) {
        this.$message.error(e);
      }
    },
    //单件盲扫退货
    async mScanRetreat() {
      let whseid = this.$store.state.wms;
      let users = this.$Cookies.get('user');
      let name = "BLINDONESCANRET";
      let receiptkey = this.routeData.receiptkey;
      try {
        let res = await this.$api.get(`/asnReturnGoods/${receiptkey}/${name}`);
        
          let storerKey = res.bean.storerkey;
          let externReceiptKey = res.bean.externreceiptkey;
          try {
            let response = await this.$api.get(`/getHttpUrl/${name}`);
              let url = `${response.bean}?whseid=${whseid}&users=${users}&receiptKey=${receiptkey}&storerKey=${storerKey}&externReceiptKey=${externReceiptKey}&name=${name}`;
              // this.$router.push({ name: "iframe", params: { url: url } });
              this.$router.push({
                name: "iframe",
                params: { url: url, title: "单件盲扫退货" },
              });
          } catch (e) {
            this.$message.error(e);
          }
        
      } catch (e) {
        this.$message.error(e);
      }
    },
    //打印上架任务
    async mPrintShelves() {
      print.grfprint("PPTASKLIST",this.$store.state.routeData.receiptkey);
    },
    //任务完成
    async completeTask() {
      try {
        let res = await this.$api.get(
          `/actionTaskdetailByReceipt/${this.routeData.receiptkey}`
        );
        console.log(res);
        
          this.$message.success(res.returnMgr);
          this.getTableData(this.page, this.tableSearhData);
        
      } catch (error) {
        this.$message.error(e);
      }
    },
    //执行完成
    async completePerform() {
      let data = [];
      if (this.tableSelectData.length > 0) {
        this.tableSelectData.forEach((item) => {
          let obj = {};
          obj.taskdetailkey = item.taskdetailkey;
          obj.toloc = item.toloc;
          obj.toid = item.toid;
          obj.fromloc = item.fromloc;
          obj.fromid = item.fromid;
          obj.lot = item.lot;
          obj.sku = item.sku;
          obj.storerkey = item.storerkey;
          obj.qty = item.qty;
          data.push(obj);
        });
      } else {
        this.$message.error(this.$t('msg.msg16'));
      }
      try {
        let res = await this.$api.post(`/moveTaskDetailForAsn`, data);
        console.log(res);
        
          this.$message.success(res.returnMgr);
          this.getTableData(this.page, this.tableSearhData);
        
      } catch (error) {
        this.$message.error(e);
      }
    },
    //单条未定/处理中数据的状态更改保存
    async changeShelvesValue() {
      console.log(this.tableSelectData);
      let data = [];
      this.tableSelectData.forEach((item, index) => {
        if (item.status == "0" || item.status == "3") {
          data.push(item);
        } else {
          this.$message.error(this.$t('msg.msg37'));
          return;
        }
      })
      try {
        let res = await this.$api.post(`/updateTaskdetailByReceipt`, data);
        
          this.$message.success(res.returnMgr);
          this.$nextTick(() => {
            this.tableData = [];
            this.getTableData(this.page, this.tableSearhData);
          });
          this.$children[3].$children[1].delSelectData(this.tableSelectData);
        
      } catch (error) {
        this.$message.error(e);
      }
    },
    //搜索的值
    searhData(data, up) {
      if (!up) {
        this.tableSearhData = data;
      } else {
        this.tableSearhData = data;
        this.getTableData(1, this.tableSearhData);
      }
    },
    selectData(data) {
      this.tableSelectData = data;
    },
    // 获取查看上架中表格的数据
    async getTableData(page, data) {
      console.log(page, data);
      try {
        this.loading = true;
        let url = this.lookUrl + this.routeData.receiptkey + "/";
        let res = await this.$api.post(`${url}${page}`, data);
        console.log(res);
        
          this.tableData = res.page.list;
          this.page = res.page.curPage;
          this.pageSize = res.page.pageSize;
          this.total = res.page.total;
        
      } catch (e) {
        this.$message.error(e.message);
      } finally {
        this.loading = false;
      }
    },
    async btnTableData(page, date, callback, searchData) {
      let url = "";
      if (this.flag) {
        url = this.poUrl;
      } else {
        url = this.lookUrl + this.routeData.receiptkey + "/";
      }
      try {
        let res = await this.$api.post(`${url}${page}`, searchData);
        callback(res);
      } catch (e) {
        this.$message.error(e);
      }
    },
    //自PO填充
    async poFill(data) {
      let arr = [];
      arr.push(data);
      try {
        let res = await this.$api.post("/storerkeyForPo", arr);
        
          let detail = this.toEmpty(this.$refs.detail.detailData);
          detail["storerkey"] = res.bean.storerkey;
          try {
            let r = await this.$api.post(`/asn/${data.pokey}`, detail);
              this.$message.success(r.returnMgr);
              this.cancel();
          } catch (e) {
            this.$message.error(e);
          }
        
      } catch (e) {
        this.$message.error(e);
      }
    },
    //查看上架
    look() {
      this.dialogFlag = true;
      this.getTableData(this.page, this.tableSearhData);
      // let arr = [];
      // if (data == undefined) {
      //   data = this.$store.state.routeData;
      // }
      // arr.push(data);
      // try {
      //   let res = await this.$api.post("/moveTaskDetailForAsn", arr);
      //   
      //     this.$message.success(res.returnMgr);
      //   } else {
      //     this.$message.error(res.returnMgr);
      //   }
      // } catch (e) {
      //   this.$message.error(e);
      // }
    },
    //保存按钮
    save() {
      let detail = this.$refs.detail.detailData;
      this.$refs.detail.$children[1].$refs.input.$refs["from"].validate(
        (valid) => {
          if (valid) {
            let data = {};
            if (this.flag) {
              let detailList = this.$refs.detailList.detailData;
              this.$refs.detailList.$children[2].$refs.input.$refs[
                "from"
              ].validate((flag) => {
                if (flag) {
                  data = {
                    ...detail,
                    receiptdetail: [{ ...detailList }],
                  };
                  this.requestHttp(data);
                }
              });
            } else {
              console.log(this);
              if (this.$store.state.temporary) {
                let detailList = this.$refs.detailList.detailData;
                this.$refs.detailList.$children[2].$refs.input.$refs[
                  "from"
                ].validate((flag) => {
                  if (flag) {
                    data = {
                      ...detail,
                      receiptdetail: [{ ...detailList }],
                    };
                    this.requestHttp(data);
                  }
                });
              } else {
                data = {
                  ...detail,
                };
                this.requestHttp(data);
              }
            }
          }
        }
      );
    },
    async requestHttp(data) {
      console.log(data);
      try {
        let res = await this.$api.post("/asn", data);
        
          this.$message.success(res.returnMgr);
          if (this.flag) {
            this.cancel();
          } else {
            this.$refs.detailList.detailNav = "1";
          }
        
      } catch (e) {
        this.$message.error(e);
      }
    },
    //弹框取消
    cancel() {
      let routerName = JSON.parse(sessionStorage.getItem("routerName"));
      let num = -1;
      if (routerName) {
        num = routerName.indexOf("asn");
      }
      if (num === -1) {
        this.$router.push({ name: "asn" });
      } else {
        num = num - 0;
        routerName.splice(num, 1);
        sessionStorage.setItem("routerName", JSON.stringify(routerName));
        this.$router.push({ name: "home1" });
      }
    },
  },
  mounted() {
    const query = this.$route.query;
    if(query.newFlag){
      this.flag = true;
    }else{
      this.flag = false;
      this.routeData = query;
    }
    // if (Object.keys(this.$store.state.skip).length !== 0) {
    //   let data = this.$store.state.skip;
    //   this.flag = data.newFlag;
    //   this.routeData = data.routeData;
    // } else if (this.$store.state.newFlag) {
    //   this.flag = true;
    // } else {
    //   this.routeData = this.$store.state.routeData;
    // }
  },
  watch: {},
  components: {
    "v-tableTitle": tableTitle,
    "v-detail": detail,
    "v-detailList": detailList,
    "v-table": table,
  },
  beforeDestroy() {
    let routerName = JSON.parse(sessionStorage.getItem("routerName"));
    let num = -1;
    if (routerName) {
      num = routerName.indexOf("asn");
    }
    if (num === -1) {
      return
    } else {
      num = num - 0;
      routerName.splice(num, 1);
      sessionStorage.setItem("routerName", JSON.stringify(routerName));
    }
  },
};
</script>

<style scoped></style>
